#include "TextureManager.h"
#include <SDL_image.h>
#include <iostream>
#include <assert.h>
#include <glut.h>

TextureManager::TextureManager()
{
}

void TextureManager::LoadTexture(const std::string& FilePath, const std::string &Tag)
{	
	std::map<std::string, Texture>::iterator it;
	it = TheTextureMap.find(Tag);

	if(it != TheTextureMap.end())
	{
		return;
	}

	Texture TempTex;
	glGenTextures(1, &TempTex.m_id);

	glBindTexture(GL_TEXTURE_2D, TempTex.m_id);
	SDL_Surface* surf = IMG_Load(FilePath.c_str());
	assert(surf);

	unsigned char* data = (unsigned char*)surf->pixels;

	int width = surf->w;
	TempTex.Width = width;

	int height = surf->h;
	TempTex.Height = height;

	int bpp = surf->format->BytesPerPixel;

	int format = GL_RGB;

	if (bpp == 4)
	{
		format = GL_RGBA;
	}

	glTexImage2D(GL_TEXTURE_2D,
		0,
		format,
		width,
		height,
		0,
		format,
		GL_UNSIGNED_BYTE,
		data);

	gluBuild2DMipmaps(
		GL_TEXTURE_2D,
		format,
		width,
		height,
		format,
		GL_UNSIGNED_BYTE,
		data);

	glEnable(GL_TEXTURE_2D);

	SDL_FreeSurface(surf);

	TheTextureMap[Tag] = TempTex;
}

void TextureManager::GetTexture(const std::string& Tag)
{
	std::map<std::string, Texture>::iterator it;
	it = TheTextureMap.find(Tag);

	if(it != TheTextureMap.end())
	{
		it->second.Bind();
	}
	else
	{
		std::cout << "No Texture " << Tag << " Exists\n";
	}
}


void TextureManager::UnBind()
{
	glBindTexture(GL_TEXTURE_2D, NULL);
}

void TextureManager::EnableSpec()
{
	glTexGeni(
		GL_S,
		GL_TEXTURE_GEN_MODE,
		GL_SPHERE_MAP);

	glTexGeni(
		GL_T,
		GL_TEXTURE_GEN_MODE,
		GL_SPHERE_MAP);

	glEnable(GL_TEXTURE_GEN_S);
	glEnable(GL_TEXTURE_GEN_T);
}

void TextureManager::DisableSpec()
{
	glDisable(GL_TEXTURE_GEN_S);
	glDisable(GL_TEXTURE_GEN_T);
}

void TextureManager::RemoveTexure(const std::string& Tag)
{
	TheTextureMap.erase(Tag);
}

int TextureManager::ReturnID(std::string Tag)
{
	std::map<std::string, Texture>::iterator it = TheTextureMap.find(Tag);

	assert(it != TheTextureMap.end());

	return it->second.m_id;
}

TextureManager::~TextureManager()
{
	TheTextureMap.clear();
}